home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 3 / BBS in a box - Trilogy III.iso / Files / Prog / B-C / C++ FAQ Reference 1.0 / C++ FAQ Reference 1.0.rsrc / TEXT_1134.txt < prev    next >
Encoding:
Text File  |  1993-06-30  |  2.0 KB  |  38 lines

  1. Technically speaking, there is no such thing.  You can get the effect you desire by a virtual 'clone()' member fn (for copy constructing), or a 'fresh()' member fn (also virtual) which constructs/creates a new object of the same class but is 'fresh' (like the 'default' [zero parameter] ctor would do).
  2.  
  3. The reason ctors can't be virtual is simple: a ctor turns raw bits into a living object.  Until there's a living respondent to a message, you can't expect a message to be handled 'the right way'.  You can think of ctors as 'class' [static] functions, or as 'factories' which churn out objects. Thinking of ctors as 'methods' attached to an object is misleading.
  4.  
  5. Here is an example of how you could use 'clone()' and 'fresh()' methods:
  6.     class Set {  //normally this would be a template
  7.     public:
  8.       virtual void insert(int);    //Set of 'int'
  9.       virtual int  remove();
  10.       //...
  11.       virtual Set& clone() const = 0;    //pure virtual; Set is an ABC
  12.       virtual Set& fresh() const = 0;
  13.       virtual ~Set() { }    //see on 'virtual destructors' for more
  14.     };
  15.  
  16.     class SetHT : public Set {
  17.       //a hash table in here
  18.     public:
  19.       //...
  20.       Set& clone() const { return *new SetHT(*this); }
  21.       Set& fresh() const { return *new SetHT(); }
  22.     };
  23.  
  24. 'new SetHT(...)' returns a 'SetHT*', so '*new' returns a SetHT&.  A SetHT is-a Set, so the return value is correct.  The invocation of 'SetHT(*this)' is that of copy construction ('*this' has type 'SetHT&').  Although 'clone()' returns a new SetHT, the caller of clone() merely knows he has a Set, not a SetHT (which is desirable in the case of wanting a 'virtual ctor').  'fresh()' is similar, but it constructs an 'empty' SetHT.
  25.  
  26. Clients can use this as if they were 'virtual constructors':
  27.     void client_code(Set& s)
  28.     {
  29.       Set& s2 = s.clone();
  30.       Set& s3 = s.fresh();
  31.       //...
  32.       delete &s2;    //relies on destructor being virtual!!
  33.       delete &s3;    // ditto
  34.     }
  35.  
  36. This fn will work correctly regardless of how the Set is implemented (hash table based, AVL tree based, etc).
  37.  
  38. See above on 'separation of interface from implementation' for more.